<template>
  <el-dialog v-model="isShow" draggable :width="720" :close-on-click-modal="false">
    <template #header>
      <el-text :type="data.flag == 'factory'?'danger':''" size="large">{{data.title}}</el-text>
    </template>
    <el-form :model="data">
      <div class="form-item-row">
        <el-form-item label="设备序列号" :label-width="sLabel[0]">
          <el-input
            v-model="data.sn"
            :disabled="hasStr('status,factory,unbind',data.flag)"
            style="width: 300px;"
          ></el-input>
        </el-form-item>
      </div>
      <div class="form-item-row">
        <el-form-item label="主板序列号" :label-width="sLabel[0]">
          <el-input
            v-model="data.board_sn"
            :disabled="data.flag == 'unbind' || data.flag == 'factory'"
            style="width: 300px;"
          ></el-input>
        </el-form-item>
      </div>
      <div class="form-item-row">
        <el-form-item label="项目单编号" :label-width="sLabel[0]">
          <el-input
            v-model="data.project_list_number"
            :disabled="hasStr('status,factory,unbind',data.flag)"
            style="width: 300px;"
          ></el-input>
        </el-form-item>
      </div>
      <div class="form-item-row">
        <el-form-item label="设备型号" :label-width="sLabel[0]">
          <el-select
            v-model="modelName"
            filterable
            remote
            reserve-keyword
            placeholder="输入设备型号关键字查询"
            @click="getModel('')"
            remote-show-suffix
            :remote-method="getModel"
            :loading="loading"
            @change="modelChange"
            :disabled="hasStr('status,factory,unbind',data.flag)"
          >
            <el-option
              v-for="item in modelOptions"
              :key="item.Id"
              :label="item.model"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
      </div>
      <div class="form-item-row" v-if="!isNull(data.modelId)">
        <el-form-item label="主板型号" :label-width="sLabel[0]">
          <el-tag size="large" type="warning">{{data.board}}</el-tag>
        </el-form-item>
        <el-form-item label="主板厂商" :label-width="sLabel[0]">
          <el-tag size="large" type="error">{{data.manufacturer}}</el-tag>
        </el-form-item>
      </div>
      <div class="form-item-row">
        <el-form-item label="所属用户" :label-width="sLabel[0]">
          <el-select
            v-model="clientName"
            filterable
            remote
            reserve-keyword
            placeholder="输入用户名称关键字查询"
            @click="getClientByName('')"
            remote-show-suffix
            :remote-method="getClientByName"
            :loading="loading"
            @change="clientChange"
            :disabled="hasStr('status,factory,unbind',data.flag)"
          >
            <el-option
              v-for="item in clientOptions"
              :key="item.Id"
              :label="item.name"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
      </div>
      <div class="form-item-row" v-if="data.dtCreate != ''">
        <el-form-item label="创建时间" :label-width="sLabel[0]">
          <span class="label">{{ data.dtCreate }}</span>
        </el-form-item>
        <el-form-item label="操作员" :label-width="sLabel[1]">
          <span class="label">{{ data.operCreate }}</span>
        </el-form-item>
      </div>
      <div class="form-item-row" v-if="data.dtUpdate != ''">
        <el-form-item label="修改时间" :label-width="sLabel[0]">
          <span class="label">{{ data.dtUpdate }}</span>
        </el-form-item>
        <el-form-item label="操作员" :label-width="sLabel[1]">
          <span class="label">{{ data.operUpdate }}</span>
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="close()">取 消</el-button>
        <!-- <el-button v-if="data.flag == 'del'" type="danger" @click="msgBox('status',data.status == cStatus[0]?'停用此设备':'取消停用')">{{
          data.status == cStatus[0] ? "停 用" : "取消停用"
        }}</el-button> -->
        <el-button v-if="data.flag == 'add'" type="primary" @click="done()" :loading="loading">确定</el-button>
        <el-button v-if="data.flag == 'factory'" type="danger" @click="msgBox('factory','终端设备即将恢复未出厂状态，将清空项目单编号、设备型号和所属用户')">恢复未出厂状态</el-button>
        <el-button v-if="data.flag == 'unbind'" type="danger" @click="msgBox('unbind','解除设备序列号与主板的绑定')">解绑主板</el-button>
        <el-button v-if="data.flag == 'bind'" type="success" @click="done()" :loading="loading">绑定主板</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { getCurrentInstance, reactive, ref } from "vue-demi";
import http from "@/axios/http";
import util from "@/assets/js/util";
import { ElMessageBox, ElNotification } from "element-plus";
import mqtt from '@/assets/js/mqtt';
export default {
  setup(props, ctx) {
    const Global = getCurrentInstance().proxy
    let user = reactive({
      id: Global.$var.user.id,
      username: Global.$var.user.username,
      power: Global.$var.user.power,
    });

    function mqttOnMsg() {
      mqtt.onMsg((t,m)=>{
        loading.value = false
        let r = JSON.parse(m)
        if (r.data.returnCode == 10000) {
          let d = r.data.data
          if (r.msgType == 120 || r.msgType == 122 || r.msgType == 123 || r.msgType == 125 || r.msgType == 126) {
            ctx.emit("done", d);
            isShow.value = false;
          }
          if (r.msgType == 61) {
            clientOptions.value = d
          }
          if (r.msgType == 165) {
          //console.log(d)
            modelOptions.value = d
          }
        }
      })
    }
    let cStatus = ref(Global.$const.STATUS_DATA);
    let sLabel = ref(["150px", "80px", "450px"]);
    let isShow = ref(false);
    let data = reactive({
      flag: "",
      title: "",
      id: "",
      status: 0,
      sn: "",
      board_sn: '',
      equipment_model: '',
      plat_user: '',
      project_list_number: '',
      terminal_type: '',
      dtCreate: "",
      operCreate: "",
      dtUpdate: "",
      operUpdate: "",
    });
    let loading = ref(false)
    function open(d) {
    //console.log(d)
      mqttOnMsg()
      data.flag = d.flag;
      modelName.value = ''
      clientName.value = ''
      if (d.flag == "add") {
        data.title = "新建设备信息";
        data.status = 0
        data.sn = ''
        data.board_sn = util.dateFormatSN()
        data.equipment_model = ''
        data.plat_user = ''
        data.project_list_number = ''
        data.terminal_type = ''
        // data.dtCreate = "";
        // data.operCreate = "";
        // data.dtUpdate = "";
        // data.operUpdate = "";
      } else {
        data.title = "编辑设备信息"
        if (d.flag == 'factory') data.title = '恢复未出厂状态将清空项目单编号、设备型号和所属用户'
        if (d.flag == 'unbind') data.title = '解绑设备序列号'
        if (d.flag == 'bind') data.title = '绑定设备序列号'
        data.id = d.Id;
        data.status = 0
        data.sn = d.sn
        data.board_sn = d.borad_sn
        data.equipment_model = d.equipment_model
        data.plat_user = d.plat_user
        modelName.value = d.equipment_model.model
        clientName.value = d.plat_user.name
        data.project_list_number = d.project_list_number
        data.terminal_type = d.terminal_type
        // data.dtCreate = d.dtCreate;
        // data.operCreate = d.operCreate;
        // data.dtUpdate = d.dtUpdate;
        // data.operUpdate = d.operUpdate;
      }
      isShow.value = true;
    }
    function close() {
      isShow.value = false;
    }
    async function done() {
      let default_equipment_model_id = Global.$const.DEFAULT_ID.model || ''
      let default_plat_user_id = Global.$const.DEFAULT_ID.client || ''
      let err = ''
      if (util.isNull(data.sn)) err = '设备序列号不能为空'
      else if (util.isNull(data.board_sn)) err = '主板序列号不能为空'
      else if (util.isNull(default_equipment_model_id)) err = '无效的系统默认设备型号'
      else if (util.isNull(default_plat_user_id)) err = '无效的系统默认用户'
      if (!util.isNull(err)) {
        ElNotification({
            type: 'warning',
            duration: 1500,
            title: '',
            message: err
          })
        return
      }
      loading.value = true
      if (hasStr('add,edit,factory,unbind,bind',data.flag)) {
        let msgCode = 120
        if (data.flag == 'edit') msgCode = 122
        if (data.flag == 'factory') msgCode = 123
        if (data.flag == 'unbind') msgCode = 125
        if (data.flag == 'bind') msgCode = 126
        let topic = mqtt.TOPIC_REQ+msgCode
        let p = {}
        p.msgType = msgCode
        p.clientId = user.id
        p.userName = user.username
        let m = {}
        if (data.flag == 'unbind') {
          // 只传id
        }
        if (data.flag == 'bind') {
          m.board_sn = data.board_sn
        }
        if (data.flag == 'add') {
          // m.status = 1
          m.sn = data.sn
          m.borad_sn = data.board_sn
          m.equipment_model_id = data.equipment_model.Id || default_equipment_model_id
          m.plat_user_id = data.plat_user.Id || default_plat_user_id
          m.project_list_number = data.project_list_number
          m.terminal_type = data.terminal_type
          p.message = {}
          p.message.equipment = JSON.stringify(m)
        } else {
          if (data.flag == 'factory') {
            m.ids = data.id
            m.project_list_number = ''
            m.equipment_model_id = default_equipment_model_id
            m.user_id = default_plat_user_id
          } else {
            m.id = data.id
          }
          p.message = m
        }
      //console.log(data.flag+'设备:',JSON.stringify(p))
        mqtt.publish(topic,JSON.stringify(p))
      }
    }
    // 确认msgBox
    function msgBox(flag,msg,title='是否确认？',cbt='确认') {
      ElMessageBox.confirm(msg, title, {
        confirmButtonText: cbt,
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (hasStr('unbind,factory'),flag) {
            done()
          }
        })
        .catch(() => {});
    }
    // 查询设备型号
    let modelName = ref("")
    let modelOptions = ref([])
    async function getModel(query) {
      let msgCode = 165
      let topic = mqtt.TOPIC_REQ+msgCode
      let g = {}
      g.msgType = msgCode
      g.clientId = user.id
      g.userName = user.username
      let m = {}
      m.model = query
      m.indexPage = 1
      m.pageSize = 10
      g.message = m
      mqtt.publish(topic,JSON.stringify(g))
    }
    function modelChange(e) {
      let mo = modelOptions.value
      for (let i in mo) {
        if (e == mo[i].Id) {
          data.equipment_model = mo[i]
        }
      }
    }

    // 查询用户信息
    let clientName = ref("")
    let clientOptions = ref([])
    function getClientByName(query) {
      let msgCode = 61
      let topic = mqtt.TOPIC_REQ+msgCode
      let g = {}
      g.msgType = msgCode
      g.clientId = user.id
      g.userName = user.username
      let m = {}
      m.name = query
      m.indexPage = 1
      m.pageSize = 10
      g.message = m
      // console.log('查询用户：',JSON.stringify(g))
      mqtt.publish(topic,JSON.stringify(g))
    }
    function clientChange(e) {
      let co = clientOptions.value
      for (let i in co) {
        if (e == co[i].Id) {
          data.plat_user = co[i]
        }
      }
    }

    function isNull(v) {
      return util.isNull(v)
    }
    function hasStr(S,k) {
      return util.hasStr(S,k)
    }

    function clearParm(f) {
      if (f == 'model') {
        data.modelId = 'clear'
        modelName.value = ''
        data.romId = 'clear'
      }
      if (f == 'client') {
        data.clientId = 'clear'
        clientName.value = ''
      }
    }

    return {
      user,cStatus,sLabel,isShow,data,loading,open,close,done,msgBox,
      modelName,modelOptions,getModel,modelChange,
      clientName,clientOptions,getClientByName,clientChange,
      isNull,hasStr,clearParm
    };
  },
};
</script>

<style lang="scss" scoped>
.form-item-row {
  display: flex;
  flex-direction: row;
  .label {
    background-color: $color-primary-away;
    // border: 1px solid $color-primary-light;
    padding: 0px 15px;
    border-radius: 1px;
  }
}
.rom-version{
  .item{
    display: flex;
    flex-direction: row;
    .code{
      width: 100px;
      margin-top: 5px;
      margin-right: 5px;
      cursor: pointer;
    }
    .name{
      width: 200px;
      margin-top: 5px;
      margin-right: 5px;
      .el-text{
        width: 180px;
      }
    }
    .btn{
      margin-top: 5px;
      margin-left: 5px;
    }
  }
}
</style>